package com.pencilisland.pay.app.mp.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.pencilisland.pay.api.bean.mp.app.MessageRequest;
import com.pencilisland.pay.api.bean.mp.app.MessageResponse;
import com.pencilisland.pay.api.bean.mp.app.QueryGoodsREQ;
import com.pencilisland.pay.api.bean.mp.app.QueryGoodsRES;
import com.pencilisland.pay.api.entity.GoodsEntity;
import com.pencilisland.pay.api.entity.GoodsImgEntity;
import com.pencilisland.pay.api.service.CacheService;
import com.pencilisland.pay.app.mp.service.MBService;
/**
* 报文逻辑处理.查询商品信息
*
* @author breeze
*/
@Service("MB_queryGoods")
public class  QueryGoodsMB implements MBService {

	@Autowired
	ObjectMapper objectMapper;
	@Autowired
	CacheService cacheService;

	@Override
	public MessageResponse process(MessageRequest request) {
		QueryGoodsREQ requestBean = getRequestBody(request);
		
		GoodsEntity goods = cacheService.retrieveGoods(requestBean.getGoodsCode());
		
		if(goods==null){
			new QueryGoodsRES(false,null,"查询商品不存在");
		}
		
		QueryGoodsRES res= new QueryGoodsRES(true,null,"OK");
		
		res.setGoodsCode(goods.getCode());
		res.setName(goods.getName());
		res.setPrice(goods.getPrice());
		res.setRemark(goods.getRemark());
		res.setStock(goods.getStock());
		res.setFreePost(goods.getFreePost());
		if(goods.getImgDetails()!=null&&!goods.getImgDetails().isEmpty()){
			List<QueryGoodsRES.ElementImgDetails> imgDetails = new ArrayList<QueryGoodsRES.ElementImgDetails>();
			for(GoodsImgEntity goodsImg:goods.getImgDetails()){
				QueryGoodsRES.ElementImgDetails element = new QueryGoodsRES.ElementImgDetails();
				element.setUrl(goodsImg.getUrl());
				element.setType(goodsImg.getType());
				imgDetails.add(element);
			}
			res.setImgDetails(imgDetails);
		}
		return res;
	}
	
	public QueryGoodsREQ getRequestBody(MessageRequest request){
		return objectMapper.convertValue(request.getBody(), QueryGoodsREQ.class);
	}

}
